package org.jeecg.modules.importExcelAnalysis.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.achAchievementExam.service.impl.AchAchievementExamServiceImpl;
import org.jeecg.modules.achachievestandarditem.entity.AchAchieveStandardItem;
import org.jeecg.modules.achachievestandarditem.service.impl.AchAchieveStandardItemServiceImpl;
import org.jeecg.modules.achexamination.entity.AchExamination;
import org.jeecg.modules.achexamination.service.impl.AchExaminationServiceImpl;
import org.jeecg.modules.achexaminationpaper.entity.AchExaminationPaper;
import org.jeecg.modules.achexaminationpaper.service.impl.AchExaminationPaperServiceImpl;
import org.jeecg.modules.classes.entity.CouClass;
import org.jeecg.modules.classes.service.impl.CouClassServiceImpl;
import org.jeecg.modules.common.utils.PoiExcelUtils;
import org.jeecg.modules.grade.entity.CouGrade;
import org.jeecg.modules.grade.service.impl.CouGradeServiceImpl;
import org.jeecg.modules.importExcelAnalysis.entity.ImportExcelAnalysis;
import org.jeecg.modules.importExcelAnalysis.mapper.ImportExcelAnalysisMapper;
import org.jeecg.modules.importExcelAnalysis.service.IImportExcelAnalysisService;
import org.jeecg.modules.importExcelAnalysis.vo.ImportExcelAnalysisVo;
import org.jeecg.modules.relation.relachstandarddistribution.entity.RelAchStandardDistribution;
import org.jeecg.modules.relation.relachstandarddistribution.service.impl.RelAchStandardDistributionServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: import_excel_analysis
 * @author: baochangrong
 * @Date: 2022-06-21
 * @Version: V1.0
 */
@Service
public class ImportExcelAnalysisServiceImpl extends ServiceImpl<ImportExcelAnalysisMapper, ImportExcelAnalysis> implements IImportExcelAnalysisService {
    @Autowired
    private ImportExcelAnalysisMapper importExcelAnalysisMapper;
    @Autowired
    private CouGradeServiceImpl couGradeService;
    @Autowired
    private CouClassServiceImpl couClassService;
    @Autowired
    private AchExaminationPaperServiceImpl achExaminationPaperService;
    @Autowired
    private AchExaminationServiceImpl achExaminationService;
    @Autowired
    private AchAchieveStandardItemServiceImpl achAchieveStandardItemService;
    @Autowired
    private RelAchStandardDistributionServiceImpl relAchStandardDistributionService;

    @Transactional
    public String analysisSubjectExaminationData(ImportExcelAnalysisVo importExcelAnalysisVo) {
        String msg = "分析结果为：";
        if (!"".equals(importExcelAnalysisVo.getClassId()) && importExcelAnalysisVo.getClassId() != null) {
            CouClass couClass = couClassService.getById(importExcelAnalysisVo.getClassId());
            if (couClass == null || "".equals(couClass.getId())) {
                msg = msg + "失败，根据选择班级没有查询到班级相关信息。请检查班级信息是否正常。";
                new IllegalArgumentException(msg);
                return msg;
            }
        } else if (!"".equals(importExcelAnalysisVo.getGradeId()) && importExcelAnalysisVo.getGradeId() != null) {
            CouGrade couGrade = couGradeService.getById(importExcelAnalysisVo.getGradeId());
            if (couGrade == null || "".equals(couGrade.getId())) {
                msg = msg + "失败，根据选择年级没有查询到年级相关信息。请检查年级信息是否正常。";
                new IllegalArgumentException(msg);
                return msg;
            }
        } else if (!"".equals(importExcelAnalysisVo.getExaminationPaperId()) && importExcelAnalysisVo.getExaminationPaperId() != null) {
            AchExaminationPaper achExaminationPaper = achExaminationPaperService.getById(importExcelAnalysisVo.getExaminationPaperId());
            if (achExaminationPaper == null || "".equals(achExaminationPaper.getId())) {
                msg = msg + "失败，根据选择试卷没有查询到试卷相关信息。请检查试卷信息是否正常。";
                new IllegalArgumentException(msg);
                return msg;
            }
        } else if (!"".equals(importExcelAnalysisVo.getExaminationId()) && importExcelAnalysisVo.getExaminationId() != null) {
            AchExamination achExamination = achExaminationService.getById(importExcelAnalysisVo.getExaminationId());
            if (achExamination == null || "".equals(achExamination.getId())) {
                msg = msg + "失败，根据选择考试没有查询到考试相关信息。请检查考试信息是否正常。";
                new IllegalArgumentException(msg);
                return msg;
            }
        }
        msg = msg + "成功！结果为：";
        int deleteSubjectExaminationDataNum = importExcelAnalysisMapper.deleteSubjectExaminationData(importExcelAnalysisVo);
        msg = msg + "清理科目成绩" + deleteSubjectExaminationDataNum + "条，";
        int analysisSubjectExaminationDataNum = importExcelAnalysisMapper.analysisSubjectExaminationData(importExcelAnalysisVo);
        msg = msg + "分析成功科目成绩" + analysisSubjectExaminationDataNum + "条，";
        int deleteExaminationDataNum = importExcelAnalysisMapper.deleteExaminationData(importExcelAnalysisVo);
        msg = msg + "清理科目分项成绩" + deleteExaminationDataNum + "条，";
        int analysisExaminationDataNum = importExcelAnalysisMapper.analysisExaminationData(importExcelAnalysisVo);
        msg = msg + "分析成功科目分项成绩" + analysisExaminationDataNum + "条，";
        return msg;
    }

    @Transactional
    public String analysisAchievementExamData(ImportExcelAnalysisVo importExcelAnalysisVo) {
        String msg = "分析结果为：";
        if (!"".equals(importExcelAnalysisVo.getClassId()) && importExcelAnalysisVo.getClassId() != null) {
            CouClass couClass = couClassService.getById(importExcelAnalysisVo.getClassId());
            if (couClass == null || "".equals(couClass.getId())) {
                msg = msg + "失败，根据选择班级没有查询到班级相关信息。请检查班级信息是否正常。";
                new IllegalArgumentException(msg);
                return msg;
            }
        } else if (!"".equals(importExcelAnalysisVo.getGradeId()) && importExcelAnalysisVo.getGradeId() != null) {
            CouGrade couGrade = couGradeService.getById(importExcelAnalysisVo.getGradeId());
            if (couGrade == null || "".equals(couGrade.getId())) {
                msg = msg + "失败，根据选择年级没有查询到年级相关信息。请检查年级信息是否正常。";
                new IllegalArgumentException(msg);
                return msg;
            }
        } else if (!"".equals(importExcelAnalysisVo.getExaminationId()) && importExcelAnalysisVo.getExaminationId() != null) {
            AchExamination achExamination = achExaminationService.getById(importExcelAnalysisVo.getExaminationId());
            if (achExamination == null || "".equals(achExamination.getId())) {
                msg = msg + "失败，根据选择考试没有查询到考试相关信息。请检查考试信息是否正常。";
                new IllegalArgumentException(msg);
                return msg;
            }
        }
        QueryWrapper<RelAchStandardDistribution> queryRelAchStandardDistribution = new QueryWrapper();
        queryRelAchStandardDistribution.eq("rel_obj_id", importExcelAnalysisVo.getExaminationId());
        queryRelAchStandardDistribution.eq("rel_obj_type", "93");
        queryRelAchStandardDistribution.eq("paper_standard_effective", "1");
        queryRelAchStandardDistribution.eq("tenant_id", importExcelAnalysisVo.getTenantId());
        List<RelAchStandardDistribution> relAchStandardDistributions = relAchStandardDistributionService.list(queryRelAchStandardDistribution);
        if (relAchStandardDistributions == null || relAchStandardDistributions.size() < 1) {
            msg = msg + "失败，根据考试ID未查询到相关联的考试计分规则关系数据，请先添加计分规则";
            new IllegalArgumentException(msg);
            return msg;
        }
        List<String> achievementStandardIdS = new ArrayList<>();
        for (RelAchStandardDistribution reldis : relAchStandardDistributions) {
            achievementStandardIdS.add(reldis.getAchievementStandardId());
        }
        QueryWrapper<AchAchieveStandardItem> queryAchAchieveStandardItem = new QueryWrapper();
        queryAchAchieveStandardItem.in("achievement_standard_id",achievementStandardIdS);
        queryAchAchieveStandardItem.in("iz_open","1");
        queryAchAchieveStandardItem.in("del_flag","0");
        queryAchAchieveStandardItem.in("tenant_id",importExcelAnalysisVo.getTenantId());
        List<AchAchieveStandardItem> achAchieveStandardItemList =achAchieveStandardItemService.list(queryAchAchieveStandardItem);
        if (achAchieveStandardItemList == null || achAchieveStandardItemList.size() < 1) {
            msg = msg + "失败，根据考试ID未查询到相关联的考试计分规则，请先添加计分规则";
            new IllegalArgumentException(msg);
            return msg;
        }

        msg = msg + "成功！结果为：";
        int deleteAchievementExamDataNum = importExcelAnalysisMapper.deleteAchievementExamData(importExcelAnalysisVo);
        msg = msg + "清理科目总成绩" + deleteAchievementExamDataNum + "条，";
        int analysisAchievementExamDataNum = importExcelAnalysisMapper.analysisAchievementExamData(importExcelAnalysisVo);
        msg = msg + "分析成功科目总成绩" + analysisAchievementExamDataNum + "条，";
        return msg;
    }

    public List<ImportExcelAnalysis> importTarget(MultipartFile file, ImportExcelAnalysisVo importExcelAnalysisVo) throws IOException {
        List<ImportExcelAnalysis> numOther = new ArrayList();
        try {
            //解析Excel,根据Excel文件创建工作簿
            //传入输入流的对象InputStream,获取Workbook
            //Workbook工作簿的高级表现形式，是sheet的上级对象。一个excel就是一个工作簿，一个工作簿含有多个工作表(sheet)
            Workbook wb = WorkbookFactory.create(file.getInputStream());
            //1.2.获取Sheet
            Sheet sheet = wb.getSheetAt(0);//参数：索引
            //获得考试名称
            String examinationName = sheet.getSheetName();
            List<String> numToo = new ArrayList();
            //合并单元格处理,获取合并行
            List<CellRangeAddress> cras = PoiExcelUtils.getCombineCell(sheet);
            //getPhysicalNumberOfRows()获得的实际行数，不一定有数据的行数。
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                //sheet.getRow(i)获取第i行的所有数据
                Row BigRow = sheet.getRow(i);
                if (BigRow == null) {
                    break;
                }
                //判断指定的单元格是否是合并单元格
                if (i == 2) {
                    int stn = BigRow.getLastCellNum();
                    for (int j = 0; j < stn; j++) {
                        if (!"".equals(BigRow.getCell(j).toString())) {
                            numToo.add(BigRow.getCell(j).toString());
                        }
                    }
                } else if (i > 2) {
                    for (int m = 0; m < numToo.size(); m++) {
                        ImportExcelAnalysis importExcelAnalysis = new ImportExcelAnalysis();
                        importExcelAnalysis.setExaminationName(examinationName);
                        importExcelAnalysis.setClassName(BigRow.getCell(0).toString());
                        importExcelAnalysis.setExaminationNo(BigRow.getCell(1).toString());
                        importExcelAnalysis.setStudentName(BigRow.getCell(2).toString());
                        importExcelAnalysis.setObjectiveExa(BigRow.getCell(3).toString());
                        importExcelAnalysis.setSubjectiveExa(BigRow.getCell(4).toString());
                        importExcelAnalysis.setTotalExa(BigRow.getCell(5).toString());
                        importExcelAnalysis.setTypeExa(BigRow.getCell(6).toString());
                        importExcelAnalysis.setTopicNum(numToo.get(m));
                        importExcelAnalysis.setTopicValue(BigRow.getCell(7 + m).toString());
                        importExcelAnalysis.setUpdateTime(null);
                        importExcelAnalysis.setUpdateBy(null);

                        importExcelAnalysis.setGradeId(importExcelAnalysisVo.getGradeId());
                        importExcelAnalysis.setClassId(importExcelAnalysisVo.getClassId());
                        importExcelAnalysis.setExaminationId(importExcelAnalysisVo.getExaminationId());
                        importExcelAnalysis.setExaminationPaperId(importExcelAnalysisVo.getExaminationPaperId());

                        numOther.add(importExcelAnalysis);
                    }
                }
            }
            return numOther;
        } catch (IOException e) {
            e.printStackTrace();
            return numOther;
        }
    }
}
